package ar.edu.uba.fi.jmit.graphvisualizer.client.widget;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;

import ar.edu.uba.fi.jmit.graphvisualizer.client.AverageMethodTimeEventService;
import ar.edu.uba.fi.jmit.graphvisualizer.client.AverageMethodTimeEventServiceAsync;
import ar.edu.uba.fi.jmit.graphvisualizer.shared.TimeValue;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class AverageMethodTimeWidget extends GraphVisualizerChart {
	
//	private String className;
//	private String monitoredMethod;
	private AverageMethodTimeEventServiceAsync service = GWT.create(AverageMethodTimeEventService.class);
	
	public AverageMethodTimeWidget() {
		addCurve(0);
		getCurve(0).setLegendLabel("Average Method Time");
		this.labelX = "When (Minutes & Seconds)";
		this.labelY = "Average Time (Seconds)";
	}

	private void addTimeValue(Date time, int value) {
		getCurve(0).addPoint(time.getTime(),Integer.valueOf(value));
		refreshYAxisTickCount(value);
	}

	protected void addValue(Map<String, Serializable> messageInfo) {
		this.addTimeValue((Date)messageInfo.get("jmit.monitorengine.key.date"), (Integer)messageInfo.get("jmit.monitorengine.methodTime.average"));
	}

	@Override
	public void configure(Map<String, Serializable> configuration) {
		this.monitorName = (String)configuration.get("monitor_name");
//		this.className = (String)configuration.get("monitored_class");
		this.applicationName = (String)configuration.get("client_application");
//		this.monitoredMethod = (String)configuration.get("jmit.monitorengine.methodTime.monitoredMethod");
		this.configureView();

	}
	
	@Override
	protected void configureView() {
		super.configureView();
		configueCurve(0, "green");
	}
	
	@Override
	public void update() {
		service.getMonitorData(applicationName, monitorName, new AsyncCallback<List<TimeValue>>() {
			
			@Override
			public void onSuccess(List<TimeValue> values) {
				getCurve(0).clearPoints();
				for(TimeValue value:values) {
					addTimeValue(value.getTime(), (Integer)value.getValue());
				}
				AverageMethodTimeWidget.super.update();
			}
			
			@Override
			public void onFailure(Throwable arg0) {
				GWT.log("AverageMethodTimeWidget.update: Failure");
			}
		});
	}

	@Override
	public String getMonitorType() {
		return "AVERAGE_METHOD_TIME";
	}

}
